﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;

namespace LiuQiuRong.Chat.Infrastructures
{
    public partial class Initialize
    {
        public static string ConnectionStringKey { get; set; }
        public static string DBName { get; set; }

        public static IContainer Container { get; private set; }

        public static IServiceProvider Configure(IServiceCollection services)
        {
            var builder = new ContainerBuilder();
            builder.Populate(services);

            builder.RegisterAssemblyModules(typeof(Initialize).Assembly);  // 注册当前程序集所有模块

            Container = builder.Build();    // 创建容器池

            return new AutofacServiceProvider(Container);   // .NET Core 默认返回IServiceProvider接口实例
        }

        /// <summary>
        /// 获取项目程序集，排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包
        /// </summary>
        /// <returns></returns>
        public static Assembly[] ReferencedAssemblies
        {

            get
            {

                var list = new List<Assembly>();
                var deps = DependencyContext.Default;
                var libs = deps.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package" && lib.Name.StartsWith("LiuQiuRong"));
                foreach (var lib in libs)
                {
                    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
                    list.Add(assembly);
                }
                return list.ToArray();
            }
        }

    }
}
